<!-- 人员花名册弹出框 -->
<template>
  <a-modal
    width="80%"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
  >
    <template #title>
      <div>人员花名册</div>
    </template>
    <div class="header" style="margin-bottom: 20px">
      <div class="header-front">
        <a-space>
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="姓名"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="nameSearch"
          />
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="手机号"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="phoneSearch"
          />
        </a-space>
      </div>
      <div></div>
    </div>

    <div class="main">
      <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
        <a-table-column :width="80">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :title="item.name"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.code"
          :width="200"
          :sortable="{
            sortDirections: ['ascend', 'descend']
          }"
        >
          <!-- 性别 -->
          <template
            v-if="item.code === 'CEE710BACA80445DE9A39622878DF04A2'"
            #cell="{ record }"
          >
            <div>
              {{
                record['CEE710BACA80445DE9A39622878DF04A2'] == 1 ? '男' : '女'
              }}
            </div>
          </template>
          <!-- <template v-if="item.code === 'humanOrigin'" #cell="{ record }">
            {{ JSON.parse(record.humanOrigin).join('-') }}
          </template>
          <template
            v-else-if="item.code === 'humanResidence'"
            #cell="{ record }"
          >
            {{ JSON.parse(record.humanResidence).join('-') }}
          </template> -->
        </a-table-column>
      </TableTurn>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  GetHumanRosterList,
  PostHumanRosterHeaderSetting,
  GetHumanRosterHeaderSetting,
  PutHumanRosterHeaderSetting,
  DelHumanRosterList
} from '@/apis/management/human/humanRoster';
import { GetBusinessModalData } from '@/apis/controltotal';
import { placeSplice } from '@/utils/utils';
import { cloneDeep } from 'lodash';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框，
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'humanRosterEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

// 表格属性
const args = reactive({
  rowSelection: {
    type: 'radio'
  }
});

const selectedListData = computed(() => tableRef.value.selectedListData);
// 新增表头
const addHeader = async () => {
  try {
    const arr: any = [];
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    })) as any;

    children.forEach((item1: any) => {
      const { subRelDetail } = item1.subDetail;
      subRelDetail.forEach((item2: any) => {
        arr.push({
          code: item2.ctlCode,
          name: item2.ctlCnName,
          isDefault: true
        });
      });
    });

    for (let index = 0; index < arr.length; index++) {
      await PostHumanRosterHeaderSetting({
        code: arr[index].code,
        name: arr[index].name,
        isDefault: arr[index].isDefault,
        type: 3,
        userId: +(localStorage.getItem('userId') as string)
      });
    }
    // arr.forEach(async ({ code, name, isDefault }: any) => {
    //   await PostHumanRosterHeaderSetting({
    //     code,
    //     name,
    //     isDefault,
    //     type: 3,
    //     userId: +(localStorage.getItem('userId') as string)
    //   });
    // });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};
let headerSetting = ref<any>([]); // 当前的表头数据

// 获取其他数据
const getData = async () => {
  try {
    const res: any = await Promise.all([
      // 获取表头数据
      GetHumanRosterHeaderSetting({
        type: 3, // 人员花名册表头默认传3,
        userId: +(localStorage.getItem('userId') as string)
      })
    ]);
    headerSetting.value = [...res[0].used, ...res[0].unused];
    headerSetting.value = headerSetting.value.sort(
      (a: any, b: any) => a.sort - b.sort
    );
    if (headerSetting.value.length === 0) {
      addHeader();
      console.log(headerSetting.value);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let modalVisiable = ref(false); // 判断是否显示表头
let headerList = ref(); // 接口获取过来的原始表头数据

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    headerList.value = await GetHumanRosterHeaderSetting({
      type: 3,
      userId: +(localStorage.getItem('userId') as string)
    });
    modalVisiable.value = !modalVisiable.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const arr: any = [];
  headerSetting.value.forEach((item: any) => {
    if (item.isDefault) {
      arr.push(item);
    }
  });
  return arr;
});

// 表头设置返回的自定义事件
const headerSave = async (used: any, unused: any) => {
  try {
    used.forEach((item: any) => (item.type = 3));
    unused.forEach((item: any) => (item.type = 3));
    await PutHumanRosterHeaderSetting({
      used,
      unused,
      userId: +(localStorage.getItem('userId') as string)
    });
    headerSetting.value = [...used, ...unused];
  } catch (error: unknown) {
    console.log(error);
  }
};

const placeCtlCode = [
  'C02BE308AEE674E3F95335AED60682954',
  'CF058C6BF648940BA96B49495CC768E20'
]; //户籍所在地、籍贯相关code
// 重组树形数据所需子方法
const controldataTreeFilter = (treeData: any) => {
  const temp = treeData.map((item2: any) => ({
    // 将控件的code赋值对应的value
    [item2.code]:
      // 如果是户籍所在地、籍贯
      placeCtlCode.includes(item2.code) ? placeSplice(item2.value) : item2.value
  }));
  let obj = {};
  temp.forEach((item: any) => {
    obj = { ...obj, ...item };
  });
  return obj;
};

const dataFilter = (data: any) => {
  const arr = data.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.positionDetailData)
  }));
  return arr;
};

let tableRef = ref();
let nameSearch = ref(''), // 姓名搜索框
  phoneSearch = ref(''); // 手机搜索框
// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    let search = 0;
    if (nameSearch.value !== '') search++;
    if (phoneSearch.value !== '') search++;
    const res: any = await GetHumanRosterList({
      ...pageData,
      name: nameSearch.value,
      ctlCode: 'C62B8DC31189847E0972B5D8F721404B1',
      search: search !== 0 ? search + '' : '',
      phone: phoneSearch.value
    });
    res.content = dataFilter(res.content);
    console.log(res.content);

    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
const onSearch = () => {
  refresh();
};
const refresh = () => {
  tableRef.value.loadData();
};
// 保存
const handleOk = () => {
  const temp = cloneDeep(
    selectedListData.value[selectedListData.value.length - 1]
  );
  console.log(temp);

  emit('humanRosterEmit', temp);
  // 清空选择器
  tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  modalVisible.value = false;
};

// 取消
const handleCancel = () => {
  // 清空选择器
  tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  modalVisible.value = false;
};
</script>

<style scoped lang="less"></style>
